package com.lzj.demo.service.impl;

import com.lzj.demo.vo.CreateOrderVo;
import com.lzj.demo.dto.TbOrder;
import com.lzj.demo.repository.TbOrderRepository;
import com.lzj.demo.service.TbOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Optional;

@Service("tbOrderService")
public class TbOrderServiceImpl implements TbOrderService {

    @Resource
    private TbOrderRepository orderRepository;

    @Transactional(rollbackFor = Exception.class)
    public TbOrder createOrder(CreateOrderVo createOrderVo){
        TbOrder order = TbOrder.create(createOrderVo);
        orderRepository.save(order);
        return order;
    }

    @Transactional(rollbackFor = Exception.class)
    public void modifyAddress(Long orderId, String address){
        Optional<TbOrder> orderOptional = orderRepository.findById(orderId);
        if (orderOptional.isPresent()){
            TbOrder order = orderOptional.get();
            order.modifyAddress(address);
            orderRepository.save(order);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void paySuccess(Long orderId){
        Optional<TbOrder> orderOptional = orderRepository.findById(orderId);
        if (orderOptional.isPresent()){
            TbOrder order = orderOptional.get();
            order.paySuccess();
            orderRepository.save(order);
        }
    }
}
